// 000

const App = getApp()
const address = require('../../../utils/city.js')
Page({
  data: {
    ktparams: {},
    form: {
      id: '', // 积分商品ID，
      buyerId: '', // 用户ID，
      integral: '', // 积分，
      sellerId: '', // 代理商ID
      contacts: '', // 收货人/联系人
      phone: '', // 联系电话，
      invite: 0, // 是否自取   0  自取  1  邮寄
      areaInfo: '请选择地址',
      addressInfo: '', // 详细地址,
    },
    invite: [{
      text: '自取',
      value: 0,
      checked: true
    }, {
      text: '邮寄',
      value: 1
    }],
    msg: {
      contacts: '请输入联系人',
      phone: '请输入联系电话',
      areaInfo: '请选择地址',
      addressInfo: '请输入详细地址'
    },
    animationAddressMenu: {},
    addressMenuIsShow: false,
    value: [0, 0, 0],
    provinces: [],
    citys: [],
    areas: [],
    province: '',
    city: '',
    area: '',
    areaInfo: '请选择地址',
    params: {

    }

  },
  onLoad(option) {

    var xinxi = JSON.parse(option.d)

    let userId = wx.getStorageSync('userId')
    let agent = wx.getStorageSync('agent')
    let integral = wx.getStorageSync('integral')

    // 如果有默认车辆的话赋值给他们的本地信息
    this.setData({
      lianxiren: wx.getStorageSync('defaultCar').linkman,
      lxfs: wx.getStorageSync('defaultCar').phone
    })




    this.setData({
      // 'form.id': integral.id,
      // 'form.integral': integral.coinValues,
      'form.buyerId': userId,
      'form.sellerId': agent.id,
      yuanjia: xinxi.y,
      // integral
      xinxi
    })

    var animation = wx.createAnimation({
      duration: 500,
      transformOrigin: "50% 50%",
      timingFunction: 'ease',
    })
    this.animation = animation
    // 默认联动显示北京
    var id = address.provinces[0].id
    this.setData({
      provinces: address.provinces,
      citys: address.citys[id],
      areas: address.areas[address.citys[id][0].id]
    })
    var m = this.data.xinxi.kait
    if (m > 0) {
      this.setData({
        yuanjia: this.data.xinxi.q
      })

    }
  },
  onShow() {},
  // 联系人
  lianxiren: function(e) {
    console.log(e.detail.value)
    this.setData({
      lianxiren: e.detail.value
    })
  },

  // 联系方式
  lxfs: function(e) {
    console.log(e.detail.value)
    this.setData({
      lxfs: e.detail.value
    })
  },
  // 详细地址
  xxdz: function(e) {
    console.log(e.detail.value)
    this.setData({
      xxdz: e.detail.value
    })
  },




  // addOrder() { // 确认下单
  //   let { form, msg } = this.data
  //   for (var i in form) {
  //     if (form.invite) {
  //       if (form[i] === '' || form[i] === '请选择地址') {
  //         wx.showToast({
  //           title: msg[i],
  //           image: '../../../assets/images/warning.png',
  //           duration: 1500
  //         })
  //         return false
  //       }
  //     } else {
  //       if ((i !== 'areaInfo' && i !== 'addressInfo') && form[i] === '') {
  //         wx.showToast({
  //           title: msg[i],
  //           image: '../../../assets/images/warning.png',
  //           duration: 1500
  //         })
  //         return false
  //       }
  //     }
  //   }
  //   if (form.invite) {
  //     form.address = form.areaInfo + ' ' + form.addressInfo
  //   }
  //   App.HttpService.intSave(form).then(res => {
  //     let data = res.data
  //     if (data.code == 200) {
  //       wx.showToast({
  //         title: '兑换成功',
  //         icon: 'success',
  //         duration: 1500
  //       })
  //       wx.navigateTo({
  //         url: '/pages/integral/list/index?back=1'
  //       })
  //       wx.removeStorageSync('integral')
  //     } else {
  //       wx.showModal({
  //         title: '提示',
  //         content: data.msg,
  //         showCancel: false
  //       })
  //     }
  //   })
  // },
  clear() {
    App.HttpService.clearCartByUser().then(res => {
      const data = res.data
      console.log(data)
    })
  },
  // inputBlur(e) { // 失去焦点时间
  //   let form = this.data.form
  //   let { key } = e.currentTarget.dataset
  //   let { value } = e.detail
  //   for (var i in form) {
  //     if (i == key) {
  //       this.setData({ ['form.' + key]: value })
  //     }
  //   }
  // },
  radioChange(e) {
    this.setData({
      'form.invite': parseInt(e.detail.value)
    })
  },




  selectDistrict(e) {
    var that = this
    if (that.data.addressMenuIsShow) { // 如果已经显示，不在执行显示动画
      return
    }
    that.startAddressAnimation(true) // 执行显示动画
  },
  startAddressAnimation(isShow) { // 执行动画
    var that = this
    if (isShow) {
      // vh是用来表示尺寸的单位，高度全屏是100vh
      that.animation.translateY(0 + 'vh').step()
    } else {
      that.animation.translateY(40 + 'vh').step()
    }
    that.setData({
      animationAddressMenu: that.animation.export(),
      addressMenuIsShow: isShow,
    })
  },



  cityCancel(e) { // 点击地区选择取消按钮
    this.startAddressAnimation(false)
  },
  citySure(e) { // 点击地区选择确定按钮
    var that = this
    var city = that.data.city
    var value = that.data.value
    that.startAddressAnimation(false)
    // 将选择的城市信息显示到输入框
    var areaInfo = that.data.provinces[value[0]].name + ' ' + that.data.citys[value[1]].name + ' ' + that.data.areas[value[2]].name
    that.setData({
      dizhi: areaInfo
    })
  },
  hideCitySelected(e) { // 点击蒙版时取消组件的显示
    this.startAddressAnimation(false)
  },
  cityChange(e) { // 处理省市县联动逻辑
    var value = e.detail.value
    var provinces = this.data.provinces
    var citys = this.data.citys
    var areas = this.data.areas
    var provinceNum = value[0]
    var cityNum = value[1]
    var countyNum = value[2]
    // 如果省份选择项和之前不一样，表示滑动了省份，此时市默认是省的第一组数据，
    if (this.data.value[0] != provinceNum) {
      var id = provinces[provinceNum].id
      this.setData({
        value: [provinceNum, 0, 0],
        citys: address.citys[id],
        areas: address.areas[address.citys[id][0].id],
      })
    } else if (this.data.value[1] != cityNum) {
      // 滑动选择了第二项数据，即市，此时区显示省市对应的第一组数据
      var id = citys[cityNum].id
      this.setData({
        value: [provinceNum, cityNum, 0],
        areas: address.areas[citys[cityNum].id],
      })
    } else { // 滑动选择了区
      this.setData({
        value: [provinceNum, cityNum, countyNum]
      })
    }
  },



  // 获取fomid
  addfrom(e) {
    console.log('form', e)
    var that = this
    var formid = e.detail.formId
    let val = e.detail.value
    console.log(formid)
    this.fid(formid);


    // 立即支付

    var t = this.data
    if (!t.lianxiren) {

      wx.showModal({
        title: '温馨提示',
        content: '联系人不能为空',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return false;
    }

    if (t.form.invite == 1) {

      if (!t.dizhi || !t.xxdz) {

        wx.showModal({
          title: '温馨提示',
          content: '请添加完整地址',
          success(res) {
            if (res.confirm) {
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }

        })

      }
    }

    if (!(/^1[3456789]\d{9}$/.test(t.lxfs))) {

      wx.showModal({
        title: '温馨提示',
        content: '请输入11位正确手机号码',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return false;
    }

    var params = this.data.params
    params.buyerId = t.form.buyerId,
      //买家id
      params.sellerId = t.form.sellerId,
      //代理商id
      params.goodsInfo = t.xinxi.i,
      //货物信息 
      params.shopId = 0,
      //商店id
      params.type = 0,
      //0单独按照普通订单处理
      params.originalPrice = t.xinxi.y,
      //原价
      params.fromId = formid
    //支付表单提交的fromid
    params.linkman = t.lianxiren,
      // 练习人
      params.phone = t.lxfs
    // 电话
    params.address = t.dizhi
    // 地址
    params.addressDetail = t.xxdz
    //详细地址
    var o = this.data.xinxi.kait
    // debugger
    if (o > 0) {
      // 开团所需要的参数集合
      var ktparams = this.data.ktparams

      ktparams.buyerId = t.form.buyerId;
      //   //买家id
      ktparams.sellerId = t.form.sellerId;
      //   //代理商id
      ktparams.multiGroupSetId = t.xinxi.id
      //  所参加的拼团id
      var pid = this.data.xinxi.pid || 0


      ktparams.groupId = pid


      // 团号
      ktparams.shopId = 0
      // 商店id
      ktparams.consignee = t.lianxiren,
        // 联系人，
        ktparams.phone = t.lxfs
      // 手机号，
      ktparams.addres = t.xxdz
      // 地址
      ktparams.fromId = formid
      // formid
      ktparams.originalPrice = this.data.yuanjia


      App.HttpService.kaituan(ktparams).then(res => {
        console.log(res, "吊起团购购买的支付")
        var n = res.data.code


        if (n == 200) {
          var config = res.data.data
          let payconfig = {
            timeStamp: config.timeStamp,
            nonceStr: config.nonceStr,
            package: config.package,
            signType: config.signType,
            paySign: config.paySign,
          }

          wx.requestPayment({
            timeStamp: config.timeStamp,
            nonceStr: config.nonceStr,
            package: config.package,
            signType: config.signType,
            paySign: config.paySign,
            success(res) {
              wx.showToast({
                title: '支付成功',
                duration: 1000,
              })
              console.log(res, "成功")
            },
            fail(res) {
              wx.showToast({
                title: '支付失败',
                icon: 'loading',
                duration: 1000,
              })
              console.log(res, "支付失败")

            }
          })



        } else {
          


          wx.showModal({
            title: '温馨提示',
            content: res.data.msg,
            success(res) {
              if (res.confirm) {
                console.log('用户点击确定')
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
          return false;



        }
      })


    } else {

      App.HttpService.dandu(params).then(res => {
        console.log(res, "吊起单独给的支付")
        // 吊起支付

        var n = res.data.code

        if (n == 200) {
       
        var config = res.data.data
  
        let payconfig = {
          timeStamp: config.timeStamp,
          nonceStr: config.nonceStr,
          package: config.package,
          signType: config.signType,
          paySign: config.paySign,
        }
        wx.requestPayment({
          timeStamp: config.timeStamp,
          nonceStr: config.nonceStr,
          package: config.package,
          signType: config.signType,
          paySign: config.paySign,
          success(res) {
            wx.showToast({
              title: '支付成功',
              duration: 1000,
            })
            console.log(res, "成功")
          },
          fail(res) {
            wx.showToast({
              title: '支付失败',
              icon: 'loading',
              duration: 1000,
            })
            console.log(res, "支付失败")

          }
        })

        } else {
          wx.showModal({
            title: '温馨提示',
            content: res.data.msg,
            success(res) {
              if (res.confirm) {
                console.log('用户点击确定')
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
          return false;

        }




      })
    }

  },
  // 传送fromid
  fid: function(e) {
    // fromid
    let uid = wx.getStorageSync('userId')
    App.HttpService.fid({
      buyerId: uid,
      fromId: e
    }).then(res => {
      console.log(res)
    })
  },
})